package com.didd.core.mybatis.handler;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;

import java.util.Date;

/**
 * mybatis-plus自动填充实现
 *
 * @author diddd
 * @date 2019/08/13
 */
public class FillMetaObjectHandler implements MetaObjectHandler {

    /**
     * 创建时间
     */
    private static final String GMT_CREATE = "gmtCreate";
    /**
     * 创建时间
     */
    private static final String ROW_CREATE_DATE = "rowCreateTime";
    /**
     * 创建时间
     */
    private static final String CREATE_DATE = "createTime";

    /**
     * 更新时间
     */
    private static final String GMT_MODIFIED = "gmtModified";
    /**
     * 更新时间
     */
    private static final String ROW_MODIFIED_DATE = "rowUpdateTime";
    /**
     * 更新时间
     */
    private static final String UPDATE_DATE = "updateTime";

    @Override
    public void insertFill(MetaObject metaObject) {
        Date now = new Date();
        if (null == this.getFieldValByName(GMT_CREATE, metaObject)) {
            this.setFieldValByName(GMT_CREATE, now, metaObject);
        }

        if (null == this.getFieldValByName(GMT_MODIFIED, metaObject)) {
            this.setFieldValByName(GMT_MODIFIED, now, metaObject);
        }

        if (null == this.getFieldValByName(ROW_CREATE_DATE, metaObject)) {
            this.setFieldValByName(ROW_CREATE_DATE, now, metaObject);
        }

        if (null == this.getFieldValByName(ROW_MODIFIED_DATE, metaObject)) {
            this.setFieldValByName(ROW_MODIFIED_DATE, now, metaObject);
        }

        if (null == this.getFieldValByName(CREATE_DATE, metaObject)) {
            this.setFieldValByName(CREATE_DATE, now, metaObject);
        }

        if (null == this.getFieldValByName(UPDATE_DATE, metaObject)) {
            this.setFieldValByName(UPDATE_DATE, now, metaObject);
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        Date now = new Date();
        this.setFieldValByName(ROW_MODIFIED_DATE, now, metaObject);
        this.setFieldValByName(UPDATE_DATE, now, metaObject);
        this.setFieldValByName(GMT_MODIFIED, now, metaObject);
    }
}
